from django_redis import get_redis_connection
from django.conf import settings
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from users.models import User
from oauth.models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS


class OauthSerializer(serializers.ModelSerializer):

    sms_code = serializers.CharField(min_length=6,max_length=6,write_only=True)
    access_token = serializers.CharField(write_only=True)
    mobile = serializers.RegexField(max_length=11,min_length=11,regex=r'^1[3-9]\d{9}$')
    token = serializers.CharField(read_only=True)
    username = serializers.CharField(read_only=True)


    class Meta:
        model = User
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'token',"username")
        extra_kwargs = {
            "password":{"min_length":8, "max_length":20, "write_only":True}
        }

    def validate(self, attrs):
        # 手机验证码验证
        red = get_redis_connection("sms_code")
        num = red.get(attrs["mobile"]).decode('utf-8')
        if attrs["sms_code"] != num:
            raise serializers.ValidationError("验证码有误")

        # openid验证
        openid = attrs['access_token']
        tjwss = TJWSS(settings.SECRET_KEY, 300)
        try:
            openid_ok = tjwss.loads(openid)
        except:
            return serializers.ValidationError("openid错误")
        else:
            if openid_ok is None:
                return serializers.ValidationError("openid已过期")
        attrs['openid_ok'] = openid_ok

        # 手机号与密码匹配验证
        try:
            # 通过手机号获取永辉对象
            user = User.objects.get(mobile=attrs['mobile'])
        # 如果用户不存在
        except:
            return attrs
        # 如果用户存在
        else:
            if not user.check_password(attrs["password"]):
                return serializers.ValidationError("密码错误")
            else:

                attrs['user'] = user
                return attrs



    def create(self, validated_data):

        user = validated_data.get('user')
        if user is None:
            user = User.objects.create_user(username=validated_data['mobile'], password=validated_data['password'],mobile=validated_data['mobile'])
        OAuthQQUser.objects.create(user=user, openid=validated_data["openid_ok"])

        # 生成jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token

        return user





